import accounting from 'accounting';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';

import CashManage from './cashManage';
import RealHoldManage from './component/RealHoldManage';
import HoldManage from './holdManage';
import style from './index.less';
import TransactionManage from './transactionManage';

import url from '../../../../assets/busi/workStation/Barra/hold_bg.png';
import { TabC, SelectC } from '../../../../comps';
import CardC from '../comps/cardC';

@Form.create()
@connect(({ loading, workStationM }) => ({ loading, workStationM }))
export default class HoldTrade extends PureComponent {
  // eslint-disable-next-line react/state-in-constructor
  state = {
    activeKey: 'HoldManage',
    productCode: undefined,
    showContent: false, // 展开收起标识
    productCodeHold: '',
    productCodeTransaction: '',
    productCodeCash: '',
    updateState: false,
    updateStateHold: false,
    updateStateTransaction: false,
    updateStateCash: false,
    minDate: moment().format('YYYY-MM-DD'),
    maxDate: moment().format('YYYY-MM-DD'),
    isEdit: false,
    realOrMock: undefined, // 判断持仓管理 组件（’1‘ -真实组合， ’2‘-虚拟组合）
  };

  componentDidMount() {
    this.props.onRef(this);
  }

  // eslint-disable-next-line react/no-deprecated
  UNSAFE_componentWillReceiveProps(nextProps) {
    const {
      form: { setFieldsValue },
    } = this.props;
    const nextInfo = JSON.stringify(nextProps.workStationM?.adjustArgs);
    const preInfo = JSON.stringify(this.props.workStationM?.adjustArgs);
    const productCode = nextProps.workStationM?.adjustArgs?.productCode; // 一键调仓的产品代码参数
    const date = nextProps.workStationM?.adjustArgs?.date; // 一键调仓的产品时间参数
    if (nextInfo !== preInfo) {
      // 设置下拉
      setFieldsValue({
        productCode,
      });
      // 收起则展开
      if (!this.state.showContent) {
        this.onExpendClick(true);
      }
      // 定位tab
      if (this.state.activeKey !== 'HoldManage') {
        this.setState({ activeKey: 'HoldManage' });
      }
      // 调用查询
      this.protifiloChange(productCode);
      const holdingInfos = nextProps.workStationM?.adjustArgs?.holdingInfos;
      // 保存信息 通知持仓管理组件更新
      this.setState({
        productCodeHold: productCode,
        date,
        holdingInfos,
      });


    }
    // 拦截产品选择设置的判断信息 type: 'workStationM/setState',
    if (nextProps.workStationM.CombinationType) {
      this.setState({
        realOrMock: nextProps.workStationM.CombinationType.portfolioType,
      });
    }

    const { activeKey } = this.state;
    if (this.props.productCode != nextProps.productCode && nextProps.productCode) {
      this.props.dispatch({
        type: 'workStationM/getTradetime',
        payload: { portfolioId: nextProps.productCode },
        callback: (res) => {
          if (res) {
            this.setState({
              minDate: res.minDate,
              maxDate: res.maxDate,
            });
          }
          this.setState({
            productCode: nextProps.productCode,
          });
          if (activeKey == 'HoldManage') {
            this.setState({
              productCodeHold: nextProps.productCode,
            });
          }
          if (activeKey == 'TransactionManage') {
            this.setState({
              productCodeTransaction: nextProps.productCode,
            });
          }
          if (activeKey == 'CashManage') {
            this.setState({
              productCodeCash: nextProps.productCode,
            });
          }
          setFieldsValue({ productCode: nextProps.productCode });
        },
      });
    }
    if (nextProps.state == 2 || nextProps.state == 4 || nextProps.state == 15 || nextProps.state == 16) {
      this.setState({
        showContent: true,
      });
    } else {
      this.setState({
        showContent: false,
      });
    }
  }

  componentWillUnmount() {
    this.props.dispatch({
      type: 'workStationM/setState',
      payload: {
        holdDataSource: {}, // 持仓列表数据
      },
    });
  }

  // 父组件调用
  // eslint-disable-next-line react/no-unused-class-component-methods
  productOnChange = (portfolioCode, operateType) => {
    if (operateType == 1 && this.state.productCode == portfolioCode) {
      this.setState({
        showContent: false,
        productCode: '',
      });
      this.props.stateOnChange('2', 'fromOperate');
    }
  };

  // tab切换
  childrentabOnclick = (activeKey) => {
    this.setState({ activeKey }, () => {
      this.getTabData();
    });
  };

  getTabData = () => {
    const { activeKey } = this.state;
    if (activeKey == 'HoldManage') {
      this.setState({
        productCodeHold: this.state.productCode,
        updateStateHold: this.state.updateState,
      });
    }
    if (activeKey == 'TransactionManage') {
      this.setState({
        productCodeTransaction: this.state.productCode,
        updateStateTransaction: this.state.updateState,
      });
    }
    if (activeKey == 'CashManage') {
      this.setState({
        productCodeCash: this.state.productCode,
        updateStateCash: this.state.updateState,
      });
    }
  };

  // 组合
  rightButton = () => {
    const {
      workStationM: { productTableList = [] },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 20,
      },
    };
    return (
      <div style={{ width: '200px', paddingRight: '8px' }}>
        <SelectC
          form={this.props.form}
          dataIndex='productCode'
          title='组合'
          dataSource={productTableList}
          allowClear={false}
          positionBody
          initialValue={this.state.productCode}
          filterOption={(
            input,
            option, // 模糊搜索value 和 title
          ) =>
            // eslint-disable-next-line implicit-arrow-linebreak
            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }
          onChange={this.protifiloChange}
          formItemLayout={formItemLayout}
          disabled={this.state.isEdit}
        />
      </div>
    );
  };

  // 组合点击响应
  protifiloChange = (productCode) => {
    // this.props.dispatch({
    //   type: 'workStationM/queryProductTableList',
    //   payload: {},
    //   callback: (data) => {
    //
    //   }
    // })
    // 优化请求
    const data = this.props.workStationM.portfolioList;
    const res = data.find((v) => v.portfolioCode == productCode);
    if (res) {
      // 设置组合类型
      this.setState(
        {
          realOrMock: res.portfolioType,
        },
        () => {
          this.props.dispatch({
            type: 'workStationM/setState',
            payload: {
              CombinationType: {
                portfolioType: res.portfolioType,
                portfolioTypeDes: res.portfolioType == 1 ? '真实' : res.portfolioType == 2 ? '模拟' : '',
                productId: res.id,
                portfolioCode: res.portfolioCode,
                portfolioId: res.portfolioId,
                isClearedCombination: productCode === 'undefined' || productCode === undefined,
              },
            },
          });
        },
      );
    } else {
      this.props.dispatch({
        type: 'workStationM/setState',
        payload: {
          CombinationType: { portfolioCode: undefined },
        },
      });
    }
    this.props.dispatch({
      type: 'workStationM/getTradetime',
      payload: { portfolioId: productCode },
      // eslint-disable-next-line no-shadow
      callback: (res) => {
        if (res) {
          this.setState({
            minDate: res.minDate,
            maxDate: res.maxDate,
          });
        }
      },
    });
    this.setState({ productCode }, () => this.getTabData());
  };

  // 展开收起响应
  onExpendClick = (showContent) => {
    this.setState({ showContent });
    this.props.stateOnChange(showContent);
  };

  // 现金和交易改变持仓组件转态
  changeEdit = () => {
    this.holdmanage.onCancel();
  };

  //
  changeUpdataState = (state) => {
    if (state == 'HoldManage') {
      this.setState({
        updateStateHold: !this.state.updateState,
      });
    }
    if (state == 'TransactionManage') {
      this.setState({
        updateStateTransaction: !this.state.updateState,
      });
    }
    if (state == 'CashManage') {
      this.setState({
        updateStateCash: !this.state.updateState,
      });
    }
    this.setState({ updateState: !this.state.updateState });
  };

  changeportfilio = (isEdit) => {
    this.setState({ isEdit });
  };

  // 刷新持仓真实组合列表
  // eslint-disable-next-line react/no-unused-class-component-methods
  refreshHoldTrade = () => {
    this.RealHoldManageRef?.getRealData();
  };

  render() {
    const { holdingInfos, productCode, showContent, productCodeHold, productCodeTransaction, productCodeCash, updateStateHold, updateStateTransaction, updateStateCash, minDate, maxDate } =
      this.state;
    const {
      state,
      workStationM: {
        holdDataSource: { totalDataSource = [], dataSource = [] },
        productTableList = [],
      },
    } = this.props;
    const productData = productTableList.filter((item) => item.value == productCode);
    return (
      <div className={style.mainBox}>
        <div className={style.openBox} style={{ display: showContent ? 'block' : 'none' }}>
          {/* 展开 */}
          <CardC
            title='持仓交易管理'
            type='2'
            showContent={showContent}
            onExpendClick={this.onExpendClick}
            content={
              <div className={style.boxContent}>
                <TabC
                  type='secondTab'
                  tabSource={[
                    {
                      title: '持仓管理',
                      key: 'HoldManage',
                      content:
                        this.state.realOrMock == '1' ? (
                          <RealHoldManage
                            showOnly={this.props.showOnly}
                            productCode={productCodeHold}
                            onRef={(ref) => (this.RealHoldManageRef = ref)}
                            changePage={this.props.changePage}
                          />
                        ) : (
                          <HoldManage
                            holdingInfos={holdingInfos || []}
                            date={this.state?.date}
                            productCode={productCodeHold}
                            OnRef={(ref) => {
                              this.holdmanage = ref;
                            }}
                            updateState={updateStateHold}
                            changeUpdataState={() => this.changeUpdataState('HoldManage')}
                            minDate={minDate}
                            maxDate={maxDate}
                            changeportfilio={this.changeportfilio}
                          />
                        ),
                    },
                    {
                      title: '交易管理',
                      key: 'TransactionManage',
                      content: (
                        <TransactionManage
                          showOnly={this.props.showOnly}
                          productCode={productCodeTransaction}
                          changeEdit={this.changeEdit}
                          updateState={updateStateTransaction}
                          changeUpdataState={() => this.changeUpdataState('TransactionManage')}
                          minDate={minDate}
                          maxDate={maxDate}
                        />
                      ),
                    },
                    {
                      title: '资金管理',
                      key: 'CashManage',
                      content: (
                        <CashManage
                          showOnly={this.props.showOnly}
                          productCode={productCodeCash}
                          changeEdit={this.changeEdit}
                          updateState={updateStateCash}
                          changeUpdataState={() => this.changeUpdataState('CashManage')}
                          minDate={minDate}
                          maxDate={maxDate}
                        />
                      ),
                    },
                  ]}
                  activeKey={this.state.activeKey}
                  onChange={this.childrentabOnclick}
                  tabBarExtraContent={this.rightButton()}
                />
              </div>
            }
          />
        </div>
        <div className={style.closeBox} style={{ display: showContent ? 'none' : 'block', overflow: 'hidden' }}>
          {/* 收起 */}
          <CardC
            title='持仓交易管理'
            type='2'
            showContent={showContent}
            onExpendClick={this.onExpendClick}
            titleIsShow={!!productCode}
            content={
              <div>
                {!productCode && <div className={style.boxContent}>选择产品后开始使用</div>}
                {productCode && (state == 1 || state == 3 || state == 13 || state == 14) && (
                  <div className={style.boxContent}>
                    <div>
                      <span>{productData && productData.length ? productData[0].title : '--'}</span>
                    </div>
                    <div>
                      该产品/组合当前持仓总市值
                      <span>
                        {' '}
                        {totalDataSource[2]?.value0 == undefined || totalDataSource[2]?.value0 == null ? '--' : accounting.formatNumber(Number(totalDataSource[2].value0), 2)}{' '}
                      </span>
                    </div>
                    <div>
                      其中共
                      <span> {dataSource.length} </span>
                      支股票，股票持仓市值为
                      <span>
                        {' '}
                        {totalDataSource[2]?.value2 == undefined || totalDataSource[2]?.value2 == null ? '--' : accounting.formatNumber(Number(totalDataSource[2].value2), 2)}{' '}
                      </span>
                      ，占比
                      <span>
                        {' '}
                        {totalDataSource[1]?.value2 == null || totalDataSource[1]?.value2 == undefined ? '--' : accounting.formatNumber(Number(totalDataSource[1].value2), 2)}{' '}
                      </span>
                      %
                    </div>
                  </div>
                )}
                {productCode && (state == 11 || state == 12) && (
                  <div className={style.boxContent}>
                    <div>
                      <span>{productData && productData.length ? productData[0].title : '--'}</span>
                    </div>
                    <div>
                      该产品/组合当前持仓总市值
                      <span>
                        {' '}
                        {totalDataSource[2]?.value0 == undefined || totalDataSource[2]?.value0 == null ? '--' : accounting.formatNumber(Number(totalDataSource[2].value0), 2)}{' '}
                      </span>
                    </div>
                    <div>
                      其中共
                      <span> {dataSource.length} </span>
                      支股票
                    </div>
                    <div>
                      股票持仓市值为
                      <span>
                        {' '}
                        {totalDataSource[2]?.value2 == undefined || totalDataSource[2]?.value2 == null ? '--' : accounting.formatNumber(Number(totalDataSource[2].value2), 2)}{' '}
                      </span>
                    </div>
                    <div>
                      占比
                      <span>
                        {' '}
                        {totalDataSource[1]?.value2 == undefined || totalDataSource[2]?.value2 == null ? '--' : accounting.formatNumber(Number(totalDataSource[1].value2), 2)}{' '}
                      </span>
                      %
                    </div>
                  </div>
                )}
                {/* eslint-disable-next-line jsx-a11y/alt-text */}
                <div className={style.closeBoxbg}>
                  <img src={url} />
                </div>
              </div>
            }
          />
        </div>
      </div>
    );
  }
}
